<template>
	<view class="pages">
		<view>
			<button @click="generateKeys">生成公私钥</button>
			<button @click="encryptMessage">加密消息</button>
			<button @click="decryptMessage">解密消息</button>
			<!-- <view>
				公钥publicKey: <textarea v-model="publicKey"></textarea>
				私钥privateKey: <textarea v-model="privateKey"></textarea>
			</view> -->
			<view>
				密文: <textarea v-model="encryptedText"></textarea>
				明文: <textarea v-model="decryptedText"></textarea>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				publicKey: null,
				privateKey: null,
				encryptedText: '',
				decryptedText: ''
			}
		},
		onShow() {
			
		},
		methods:{
			generateKeys() {
				window.crypto.subtle.generateKey({
						name: "RSA-OAEP",
						modulusLength: 2048,
						publicExponent: new Uint8Array([1, 0, 1]),
						hash: "SHA-256",
					},
					true,
					["encrypt", "decrypt"]
				).then((key) => {
					this.publicKey = key.publicKey;
					this.privateKey = key;
					console.log("this.publicKey:",this.publicKey);
					console.log("this.privateKey:",this.privateKey);
				});
			},
			encryptMessage() {
				const message = new TextEncoder("utf-8").encode("Hello, World!");
				window.crypto.subtle.encrypt({
						name: "RSA-OAEP",
					},
					this.publicKey,
					message
				).then((encrypted) => {
					this.encryptedText = Buffer.from(encrypted).toString('base64');
				});
			},
			decryptMessage() {
				const encryptedBuffer = Buffer.from(this.encryptedText, 'base64');
				console.log("encryptedBuffer：",encryptedBuffer);
				window.crypto.subtle.decrypt({
						name: "RSA-OAEP",
					},
					this.privateKey,
					encryptedBuffer
				).then((decrypted) => {
					this.decryptedText = new TextDecoder("utf-8").decode(decrypted);
				});
			},
		}
	}
</script>

<style>
</style>